package com.xudow.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.activeshare.edu.ucenter.models.base.SysSubject;
import com.activeshare.edu.ucenter.models.wor.WrongTopicWithInfo;
import com.xudow.app.R;
import com.xudow.app.ui.task.SubjectsTask;
import com.xudow.app.util.Maps;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 科目选择Activity
 *
 * @author lukecheng
 */
public class SubjectsActivity extends BaseActivity {

    private List<SysSubject> subjects;
    private List<String> subjectNames;

    private SubjectsTask subjectsTask;

    private String studentId;

    private ListView listView;
    private ArrayAdapter<String> subjectAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subjects);

        studentId = getIntent().getStringExtra("studentId");

        listView = (ListView) findViewById(R.id.list);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent data = new Intent();
                data.putExtra("subjectName", subjects.get(position).getName());
                data.putExtra("subjectId", "" + subjects.get(position).getId());

                setResult(RESULT_OK, data);
                finish();
            }
        });

        HashMap<String, String> params = Maps.newHashMap();
        params.put("studentid", studentId);

        subjectsTask = new SubjectsTask(this, subjectsTaskHandler);
        addTask(subjectsTask);
        subjectsTask.execute(params);
    }

    Handler subjectsTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (SubjectsTask.SUCCESS == msg.what) {
                SysSubject[] subjectsArr = (SysSubject[]) msg.getData().getSerializable("subjects");

                subjects = new ArrayList<SysSubject>();

                for (SysSubject s : subjectsArr) {
                    subjects.add(s);
                }

                onSubjectSuccess();
            }
        }
    };

    private void onSubjectSuccess() {
        subjectNames = new ArrayList<String>();

        for (SysSubject subject : subjects) {
            subjectNames.add(subject.getName());
        }

        subjectAdapter = new ArrayAdapter<String>(this, R.layout.item_subject_list, subjectNames);
        listView.setAdapter(subjectAdapter);
    }

    public void onBackBtnClick(View view) {
        finish();
    }


}
